#include "sensormanager.h"
#include "config.h"
#include <QDebug>
#include <QDateTime>
#include <QRandomGenerator>

SensorManager::SensorManager(QObject *parent)
    : QObject(parent)
    , m_sensorsInitialized(false)
    , m_readTimer(new QTimer(this))
    , m_samplingInterval(2000)  // 2秒
    , m_isMonitoring(false)
    , m_temperatureOffset(0.0)
    , m_humidityOffset(0.0)
    , m_lightOffset(0)
{
    initializeSensors();
    
    // 设置定时器
    m_readTimer->setInterval(m_samplingInterval);
    connect(m_readTimer, &QTimer::timeout, this, &SensorManager::readSensors);
    
    // 初始化数据
    m_currentData.temperature = 0.0;
    m_currentData.humidity = 0.0;
    m_currentData.lightLevel = 0;
    // m_currentData.motionDetected = false; // 运动检测已删除
    m_currentData.timestamp = 0;
    
    m_previousData = m_currentData;
    
    qDebug() << "传感器管理器初始化完成";
}

SensorManager::~SensorManager()
{
    stopMonitoring();
}

void SensorManager::initializeSensors()
{
    qDebug() << "初始化传感器...";
    
    // 在实际硬件上，这里会初始化I2C或其他传感器接口
    // 目前使用模拟数据
    
    m_sensorsInitialized = true;
    qDebug() << "传感器初始化完成";
}

void SensorManager::startMonitoring()
{
    if (!m_sensorsInitialized) {
        emit sensorError("传感器未初始化");
        return;
    }
    
    if (m_isMonitoring) {
        qDebug() << "传感器已在监控中";
        return;
    }
    
    m_isMonitoring = true;
    m_readTimer->start();
    qDebug() << "开始传感器监控，采样间隔:" << m_samplingInterval << "ms";
}

void SensorManager::stopMonitoring()
{
    if (!m_isMonitoring) {
        return;
    }
    
    m_isMonitoring = false;
    m_readTimer->stop();
    qDebug() << "停止传感器监控";
}

void SensorManager::readSensors()
{
    QMutexLocker locker(&m_dataMutex);
    
    m_previousData = m_currentData;
    
    // 读取各个传感器
    m_currentData.temperature = readTemperature();
    m_currentData.humidity = readHumidity();
    m_currentData.lightLevel = readLightLevel();
    // m_currentData.motionDetected = readMotionSensor(); // 运动检测已删除
    m_currentData.timestamp = QDateTime::currentMSecsSinceEpoch();
    
    // 验证数据
    if (!validateSensorReading(TemperatureSensor, m_currentData.temperature) ||
        !validateSensorReading(HumiditySensor, m_currentData.humidity) ||
        !validateSensorReading(LightSensor, m_currentData.lightLevel)) {
        qWarning() << "传感器数据异常";
        return;
    }
    
    // 发送信号（仅在数据变化时）
    if (qAbs(m_currentData.temperature - m_previousData.temperature) > 0.5) {
        emit temperatureChanged(m_currentData.temperature);
    }
    
    if (qAbs(m_currentData.humidity - m_previousData.humidity) > 1.0) {
        emit humidityChanged(m_currentData.humidity);
    }
    
    if (qAbs(m_currentData.lightLevel - m_previousData.lightLevel) > 10) {
        emit lightLevelChanged(m_currentData.lightLevel);
        emit lightChanged(m_currentData.lightLevel);
    }
    
    // if (m_currentData.motionDetected && !m_previousData.motionDetected) {
    //     emit motionDetected();
    // } // 运动检测已删除
    
    emit sensorDataUpdated(m_currentData);
}

double SensorManager::readTemperature()
{
    // 在实际硬件上，这里会从温度传感器读取数据
    // 目前生成模拟数据：20-35°C范围内的温度
    static double baseTemp = 25.0;
    
    // 添加一些随机变化和滤波
    double rawTemp = baseTemp + (QRandomGenerator::global()->bounded(200) - 100) / 50.0;
    
    // 应用校准偏移
    rawTemp += m_temperatureOffset;
    
    // 简单滑动平均滤波
    m_temperatureBuffer.append(rawTemp);
    if (m_temperatureBuffer.size() > FILTER_SIZE) {
        m_temperatureBuffer.removeFirst();
    }
    
    double filteredTemp = 0.0;
    for (double temp : m_temperatureBuffer) {
        filteredTemp += temp;
    }
    filteredTemp /= m_temperatureBuffer.size();
    
    return filteredTemp;
}

double SensorManager::readHumidity()
{
    // 模拟湿度数据：40-80%范围
    static double baseHumidity = 60.0;
    
    double rawHumidity = baseHumidity + (QRandomGenerator::global()->bounded(200) - 100) / 20.0;
    rawHumidity += m_humidityOffset;
    
    // 滤波
    m_humidityBuffer.append(rawHumidity);
    if (m_humidityBuffer.size() > FILTER_SIZE) {
        m_humidityBuffer.removeFirst();
    }
    
    double filteredHumidity = 0.0;
    for (double humidity : m_humidityBuffer) {
        filteredHumidity += humidity;
    }
    filteredHumidity /= m_humidityBuffer.size();
    
    return qBound(0.0, filteredHumidity, 100.0);
}

int SensorManager::readLightLevel()
{
    // 模拟光照数据：0-1000 lux范围
    static int baseLight = 300;
    
    int rawLight = baseLight + QRandomGenerator::global()->bounded(400) - 200;
    rawLight += m_lightOffset;
    
    // 滤波
    m_lightBuffer.append(rawLight);
    if (m_lightBuffer.size() > FILTER_SIZE) {
        m_lightBuffer.removeFirst();
    }
    
    int filteredLight = 0;
    for (int light : m_lightBuffer) {
        filteredLight += light;
    }
    filteredLight /= m_lightBuffer.size();
    
    return qBound(0, filteredLight, 1000);
}

// bool SensorManager::readMotionSensor() // 运动检测已删除
// {
//     // 模拟运动检测：10%概率检测到运动
//     return QRandomGenerator::global()->bounded(100) < 10;
// }

bool SensorManager::validateSensorReading(SensorType type, double value)
{
    switch (type) {
    case TemperatureSensor:
        return (value >= -40.0 && value <= 100.0); // 合理的温度范围
    case HumiditySensor:
        return (value >= 0.0 && value <= 100.0);   // 湿度百分比
    case LightSensor:
        return (value >= 0 && value <= 10000);     // 光照强度范围
    // case MotionSensor: // 运动检测已删除
        return true; // 布尔值总是有效的
    }
    return false;
}

void SensorManager::calibrateSensors()
{
    qDebug() << "开始传感器校准...";
    
    // 停止监控进行校准
    bool wasMonitoring = m_isMonitoring;
    if (m_isMonitoring) {
        stopMonitoring();
    }
    
    // 读取多次取平均值进行校准
    QList<double> tempReadings;
    QList<double> humidityReadings;
    QList<int> lightReadings;
    
    for (int i = 0; i < 10; ++i) {
        tempReadings.append(readTemperature());
        humidityReadings.append(readHumidity());
        lightReadings.append(readLightLevel());
        QThread::msleep(100);
    }
    
    // 计算偏移量（这里假设标准值为已知）
    double avgTemp = 0.0, avgHumidity = 0.0;
    int avgLight = 0;
    
    for (double temp : tempReadings) avgTemp += temp;
    for (double humidity : humidityReadings) avgHumidity += humidity;
    for (int light : lightReadings) avgLight += light;
    
    avgTemp /= tempReadings.size();
    avgHumidity /= humidityReadings.size();
    avgLight /= lightReadings.size();
    
    // 假设标准值（在实际应用中应该从配置文件或用户输入获取）
    double standardTemp = 25.0;
    double standardHumidity = 60.0;
    int standardLight = 300;
    
    m_temperatureOffset = standardTemp - avgTemp;
    m_humidityOffset = standardHumidity - avgHumidity;
    m_lightOffset = standardLight - avgLight;
    
    qDebug() << "校准完成:";
    qDebug() << "温度偏移:" << m_temperatureOffset;
    qDebug() << "湿度偏移:" << m_humidityOffset;
    qDebug() << "光照偏移:" << m_lightOffset;
    
    // 恢复监控状态
    if (wasMonitoring) {
        startMonitoring();
    }
}

void SensorManager::setSamplingInterval(int milliseconds)
{
    m_samplingInterval = qMax(100, milliseconds); // 最小100ms
    m_readTimer->setInterval(m_samplingInterval);
    qDebug() << "设置采样间隔为:" << m_samplingInterval << "ms";
}

// void SensorManager::processMotionData() // 运动检测已删除
// {
//     // 运动数据后处理
//     // 可以在这里实现运动检测的去抖动逻辑
// } 